package com.jjty.dataGenerator.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Set;

/**
 * @Author: huangyulong
 * @createTime: 2023-09-19 15:04
 * @Description: https请求工具
 */
public class HttpsRequestUtils {

    /**
     * 发送http请求
     * @param url
     * @param header
     * @return 响应体json数据
     */
    public static String sendPostHttpsNoneSSL(String url, Map<String,String> header, String json, String charset) throws IOException {
        CloseableHttpClient client = null;
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            //digest
            client = HttpClients.custom().setSSLSocketFactory(ssf).build();

            HttpPost post = new HttpPost(url);
            Set<String> set = header.keySet();
            for (String key : set) {
                post.setHeader(key, header.get(key));
            }
            if (StringUtils.isNotEmpty(json)) {
                HttpEntity entity = new StringEntity(json, charset);
                post.setEntity(entity);
            }
            CloseableHttpResponse response = client.execute(post);
            try{
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    return EntityUtils.toString(resEntity);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                response.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
        return null;
    }

}
